<?php
namespace app\wechat\service;
use Curl\CurlHttpRequest;
use EasyWeChat\Factory;
use Symfony\Component\Cache\Adapter\RedisAdapter;
use think\facade\Cache;

class Open
{
    public $config;
    public $openPlatform;
    public function __construct($confg=[])
    {
        if(!$confg)
        {
            $confg = get_option("wechat_official")['official'];
        }
        $this->config = array_merge($confg,config("official."));
      /*  $this->openPlatform = Factory::openPlatform($this->config);
        $client = new \Predis\Client('127.0.0.1:6379');
        $cache = new RedisAdapter($client);
        $this->openPlatform->rebind('cache', $cache);*/
    }

    /**
     * @Notes:消息事件处理
     * @User: chenping
     * @email: 375129701@qq.com
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function service()
    {
        return $this->openPlatform->server->serve();
    }


    /**
     * @Notes:获取授权用户信息
     * @User: chenping
     * @email: 375129701@qq.com
     * @param string $appid
     * @return mixed
     */
    public function getOauthUserInfo($appid='')
    {
       return $this->openPlatform->getAuthorizer($appid);
    }

    /**
     * @Notes:发起网页授权代码登陆 （网页端扫码登录） 需要第三方平台支持
     * @User: chenping
     * @email: 375129701@qq.com
     * @param string $url
     */
    public function oauth($callbackUrl="")
    {
        $option = $this->config;
        $callbackUrl =$callbackUrl?urldecode($callbackUrl):urldecode(url("wechat/oauth/wxcallback",'','',true));
        $url = "https://open.weixin.qq.com/connect/qrconnect?appid={$option['app_id']}&redirect_uri={$callbackUrl}&response_type=code&state=state&scope=snsapi_login";
        header("Location:{$url}");
    }

    /**
     * @Notes:获取token
     * @User: chenping
     * @email: 375129701@qq.com
     * @param $code
     */
    public function access_token($code)
    {
        $option = $this->config;
        $access_token  = (new CurlHttpRequest())->curlHttpGet("https://api.weixin.qq.com/sns/oauth2/access_token",[
            "appid" => $option['app_id'],
            "secret" => $option['secret'],
            "grant_type" => "authorization_code",
            "code" => $code
        ]);
        return json_decode($access_token,true);
    }

    /**
     * @Notes:获取用户信息
     * @User: chenping
     * @email: 375129701@qq.com
     * @param $token
     * @return mixed|string
     */
    public function get_userinfo($token)
    {
        $user   = (new CurlHttpRequest())->curlHttpGet("https://api.weixin.qq.com/sns/userinfo",[
            "access_token" => $token['access_token'],
            "openid"       => $token['openid'],
            "lang"         => "zh_CN"
        ]);
        return json_decode($user,true);
    }








}